<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\service\Region as RegionService;
use app\admin\service\Store as StoreService;

use think\Request;

class Store extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->defaultOrder = 'create_date DESC';

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            $regions = RegionService::getDistrict();

            $this->assign('regions', $regions);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){

        return parent::edit($request);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();

            if ($data['id']) {
                // Update data
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                $logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_update';
            } else {
                // Insert data
                $data['id'] = Helper::getUUID();
                $data['create_date'] = date('Y-m-d H:i:s');
                $result = $model->save($data);
                $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_insert';
            }

            if($result !== false) {
                // Query执行后的操作
                $model->$afterAction($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['store_type']) && $param['store_type']){
            $where['store_type'] = $param['store_type'];
        }

        return $where;
    }

    /**
     * 导出数据
     */
    public function export(){
        $result = StoreService::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg'], url('admin/store/index'));
        }

        return redirect('admin/store/index');
    }

}